#!/bin/bash

# ./shell.sh jarName start
# 设置环境变量
#export JAVA_HOME=/usr/local/jdk1.8.0_201
#export PATH=$PATH:$JAVA_HOME/bin
#输入的jar包名称
#第一个参数为jar包名称
jar_name=$1
pid_file="/home/mu-message/${jar_name}.pid"
# jar包的路径
jar_path="/home/mu-message/${jar_name}.jar"
# 备份的路径
backup_path="/home/mu-message/backup/${jar_name}-$(date +%Y%m%d%H%M%S).jar"
#第二个参数为命令
case "$2" in
    #如果是start 启动命令
    start)
        #如果存在已启动的该jar包进程，则先杀掉进程
        if [ -f "$pid_file" ] && kill -0 $(cat "$pid_file") > /dev/null 2>&1; then
            echo "Process already running with pid $(cat $pid_file)"
            exit 1
        fi
        cp "$jar_path" "$backup_path"
        #启动jar包
        nohup java -jar $jar_path > /dev/null 2>&1 &
        #把进程号存入进程文件中
        echo $! > "$pid_file"
        echo "Started process with pid $(cat $pid_file)"
        ;;
    restart)
        #如果存在已启动的该jar包进程，则先杀掉进程
        if [ -f "$pid_file" ] && kill -0 $(cat "$pid_file") > /dev/null 2>&1; then
            echo "Stopping process with pid $(cat $pid_file)"
            kill $(cat "$pid_file")
            sleep 3
        fi
        cp "$jar_path" "$backup_path"
        echo "Starting process"
        nohup java -jar $jar_path > /dev/null 2>&1 &
        echo $! > "$pid_file"
        echo "Started process with pid $(cat $pid_file)"
        ;;
    stop)
        #如果存在已启动的该jar包进程，杀掉进程
        if [ -f "$pid_file" ] && ki ll -0 $(cat "$pid_file") > /dev/null 2>&1; then
            echo "Stopping process with pid $(cat $pid_file)"
            kill $(cat "$pid_file")
            rm "$pid_file"
            echo "Stopping success"
        else
            echo "Process not running"
            exit 1
        fi
        ;;
    *)
        echo "Usage: $0 <jar_name> {start|restart|stop}"
        exit 1
        ;;
esac

